package dao;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Database {

    public boolean backup(String path) {
	String command = "cmd /c mysqldump -uroot -p123456 --set-charset=utf8 assistedlearning";
	PrintWriter p = null;
	BufferedReader reader = null;
	String dateString = (new SimpleDateFormat("yyyyMMddhhMMss")).format(new Date());
	try {
	    StringBuffer buffer = new StringBuffer(path);
	    if(!path.endsWith("\\")){
		buffer.append("\\");
	    }
	    buffer.append(dateString).append(".sql");
	    p = new PrintWriter(new OutputStreamWriter(new FileOutputStream(
		    buffer.toString()), "utf8"));
	    Process process = Runtime.getRuntime().exec(command);
	    InputStreamReader inputStreamReader = new InputStreamReader(
		    process.getInputStream(), "utf8");
	    reader = new BufferedReader(inputStreamReader);
	    String line = null;
	    while ((line = reader.readLine()) != null) {
		p.println(line);
	    }
	    p.flush();
	} catch (IOException e) {
	    e.printStackTrace();
	} finally {
	    try {
		if (reader != null) {
		    reader.close();
		}
		if (p != null) {
		    p.close();
		}
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}
	return true;
    }
    
    public static void backup2(){
	
        String str="mysqldump -uroot -proot --opt assistedlearning >  e:\\abc\\test.sql";    
        try {  
                Runtime rt=Runtime.getRuntime();
                rt.exec("cmd /c "+str);
                System.out.println("successly!");
        } catch (IOException e) {  
                e.printStackTrace();  
                System.out.println("something wrong!");                
    
        }  
        
}
    public static void main(String[] args){
	Database database = new Database();
//	database.backup2();
	if(database.backup("e:\\abc")){
	    System.out.println("备份成功！");
	}
    }
}
